<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validate-trigger="submit" :label-width="100" :label-align="'right'"
			err-show-type="toast">
			<uni-forms-item name="goods_sn" label="货品编码" required>
				<uni-easyinput placeholder="货品编码" v-model="formData.goods_sn" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="name" label="货品名称" required><uni-easyinput placeholder="货品名称" v-model="formData.name"
					trim="both"></uni-easyinput></uni-forms-item>
			<uni-forms-item name="type" label="规格型号" required><uni-easyinput placeholder="规格型号" v-model="formData.type"
					trim="both"></uni-easyinput></uni-forms-item>
			<uni-forms-item name="danwei" label="计量单位" required>
				<uni-easyinput placeholder="计量单位" v-model="formData.danwei"
					trim="both"></uni-easyinput></uni-forms-item>
			<uni-forms-item name="unit_id" label="进货单位" required>
				<uni-data-select collection="unit" field="_id as value, name as text" @change="change"
					v-model="formData.unit_id" :localdata="range"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="keywords" label="关键字" required>
				<uni-easyinput placeholder="商品关键字，为搜索引擎收录使用" v-model="formData.keywords" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="price" label="成本单价" required><uni-easyinput placeholder="成本单价" type="number"
					v-model="formData.price"></uni-easyinput></uni-forms-item>
			</uni-forms-item><uni-forms-item name="sj_count" label="实际库存" required>
				<uni-easyinput placeholder="实际库存" type="number" v-model="formData.sj_count"></uni-easyinput>
			</uni-forms-item>
			</uni-forms-item><uni-forms-item name="wqx_count" label="未清洗" required>
				<uni-easyinput placeholder="未清洗" type="number" v-model="formData.wqx_count"></uni-easyinput>
			</uni-forms-item>
			</uni-forms-item><uni-forms-item name="yqx_count" label="已清洗" required>
				<uni-easyinput placeholder="已清洗" type="number" v-model="formData.yqx_count"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="goods_desc" label="产品中文描述"><uni-easyinput placeholder="产品中文描述"
					v-model="formData.goods_desc" trim="both"></uni-easyinput></uni-forms-item>
			<uni-forms-item name="remain_count" label="库存数量" required>
				<uni-easyinput placeholder="库存数量" type="number" v-model="formData.remain_count"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="goods_fj" label="货品附件">
				<uni-file-picker v-model="formData.goods_fj" fileMediatype="all" :multiple="true" :max="5" :size="10"
					:file-type="['file']" :extensions="['.zip', '.rar','.7z']" :show-delete="true" mode="grid"
					@select="select" @progress="progress" @success="success" @fail="fail" />

			</uni-forms-item>

			<view class="uni-button-group"><button type="primary" class="uni-button" @click="submit">提交</button></view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/opendb-mall-goods.js';

	const db = uniCloud.database();
	const dbCollectionName = 'opendb-mall-goods';

	function getValidator(fields) {
		let result = {};
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key];
			}
		}
		return result;
	}

	export default {
		data() {
			let formData = {
				category_id: '',
				goods_sn: '',
				price: null,
				name: '',
				type: '',
				unit: '',
				keywords: '',
				goods_desc: '',
				goods_fj: [],
				goods_thumb: '',
				goods_banner_imgs: [],
				remain_count: null,
				zm_count: null,
				sj_count: null,
				wqx_count: null,
				yqx_count: null,
				month_sell_count: null,
				total_sell_count: null,
				comment_count: null,
				is_real: null,
				is_on_sale: null,
				is_alone_sale: null,
				is_best: null,
				is_new: null,
				is_hot: null,
				add_date: null,
				last_modify_date: null,
				seller_note: '',
			};
			return {
				formDataId: -1,
				imageValue: [],
				formData,
				range: [],
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			};
		},
		watch: {
			'formData.price': {
				handler(newVal, oldVal) {
					if (newVal > 0 && this.formData.remain_count > 0) {
						this.formData.all_price = parseFloat((newVal * this.formData.remain_count).toFixed(4));

					}
				}
			},
			'formData.remain_count': {
				handler(newVal, oldVal) {
					if (this.formData.price > 0 && newVal > 0) {
						this.formData.all_price = parseFloat((newVal * this.formData.price).toFixed(4));
						console.log(this.formData.all_price);
					}
				}
			},
			deep: true
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id;
				this.formDataId = id;
				this.getDetail(id);
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules);
		},
		methods: {
			// 获取上传状态
			select(e) {
				console.log('选择文件：', e)
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功', e)
				// this.formData.goods_fj = e.tempFiles[0].url
				console.log(e.tempFiles[0].url, this.formData);
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			change(e) {
				console.log(e);
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				});
				this.$refs.form
					.validate()
					.then(res => {
						return this.submitForm(res);
					})
					.catch(() => {})
					.finally(() => {
						uni.hideLoading();
					});
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				if (this.formDataId == -1) {
					db.collection(dbCollectionName)
						.add(value)
						.then(res => {
							uni.showToast({
								title: '新增成功'
							});
							this.getOpenerEventChannel().emit('refreshData');
							setTimeout(() => uni.navigateBack(), 500);
						})
						.catch(err => {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							});
						})
						.finally(() => {
							uni.hideLoading();
						});
				} else {

					return db
						.collection(dbCollectionName)
						.doc(this.formDataId)
						.update(value)
						.then(res => {
							uni.showToast({
								icon: 'none',
								title: '修改成功'
							});
							this.getOpenerEventChannel().emit('refreshData');
							setTimeout(() => uni.navigateBack(), 500);
						})
						.catch(err => {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							});
						});
				}


			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				});

				db.collection(dbCollectionName)
					.doc(id)
					.get()
					.then(res => {
						const data = res.result.data[0];
						if (data) {
							this.formData = data;
						}
					})
					.catch(err => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						});
					})
					.finally(() => {
						uni.hideLoading();
					});
			}
		}
	};
</script>

<style>
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;
	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
	}
</style>